<template>
  <n-card :bordered="false">
    <div>
      <basic-form
        :schemas='schemas'
        :labelWidth='labelWidth'
        :gridProps='gridProps'
        @handleSearch='handleSearch'
        :pageParams='pageParams'
        size='small'
        ref='roleSearchRef'
      >
      </basic-form>
      
      <basic-table
        :title='title'
        :data='data'
        :columns='columns'
        :loading="loading"
      >
        <template #tableTitle>
          <n-space>
            <n-button type='info' @click='handleAdd()'>添加</n-button>
          </n-space>
        </template>      
      </basic-table>
    </div>

    <n-modal
      v-model:show='showModal'
      :show-icon="false"
      style="width:650px"
      title="添加角色"
      preset="dialog">
      <n-form :model='form' ref='formRef'>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="角色名称" path="roleName">
            <n-input v-model:value="form.roleName" placeholder="请输入名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label='权限标识' path='roleKey'>
            <n-input v-model:value="form.roleKey" placeholder="请输入名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="显示顺序" path="orderNum">
            <n-input v-model:value="form.orderNum" placeholder="请输入名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label='状态' path='status'>
            <n-radio-group v-model:value="form.status" name="status">
              <n-space>
                <n-radio
                  v-for='item in statusOption'
                  :key='item.dictValue'
                  :value='item.dictValue'
                  :label='item.dictValue'>{{ item.dictLabel }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label='菜单权限' path='perms'>
            <n-tree
              v-model:value="form.perms"
              block-line
              cascade
              checkable
              label-field='menuName'
              key-field='id'
              :data='menuList'
              :checked-keys='checkedKeys'
              :expanded-keys='expandedKeys'
              @update:checked-keys='updateCheckedKeys'
              @update:expanded-keys='updateExpandedKeys'
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label='备注' path='remark'>
            <n-input v-model:value="form.remark" type="textarea" :autosize="{ minRows: 3 }" placeholder="请输入备注信息" />
          </n-form-item-gi>
        </n-grid>
      </n-form>

      <template #action>
        <n-space justify="center">
          <n-button @click='() => (showModal=false)'>取消</n-button>
          <n-button @click='submitForm' :loading='btnLoading' type="info">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { onMounted, ref, unref, reactive, getCurrentInstance, computed, h } from 'vue'
  import { BasicTable } from '@/components/Table'
  import { BasicForm } from '@/components/Form'
  import { list } from '@/api/commonApi'
  import { listMenu, getTreeSelectByRoleId} from '@/api/system/menu'
  import { addRole, updateRole } from '@/api/system/role'
  import { OrderType } from '@/enums/tableEnum'
  import { useStore } from 'vuex'
  import OperateButton from '@/components/OperateButton/index.vue'

  const store = useStore()
  const internalInstance = getCurrentInstance()
  const data = ref([])
  const statusOption = computed(() => store.getters.statusOption)

  const { selectDictLabel, handleTree, $message, $dialog } = internalInstance?.appContext.config.globalProperties

/** 分页查询参数 */
  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'create_time',
    isAsc: OrderType.DESC
  })

  /** 查询条件label宽度 */
  const labelWidth = 120
  /** 查询条件表单布局 */
  const gridProps = { cols: '1 500:2 800:3 1000:4 1250:5 1500:6' }
  /** 查询条件字段组件 */
  const schemas = [
    {
      field: 'roleName',
      component: 'NInput',
      label: '角色名称',
      placeholder: '请输入角色名称',
    }, {
      field: 'roleKey',
      component: 'NInput',
      label: '权限标识',
      placeholder: '请输入权限标识'
    }, {
      field: 'status',
      component: 'NRadio',
      label: '状态',
      componentProps: {
        options: [...statusOption.value]
      }
    }, {
      field: 'birthday',
      component: 'NDatePicker',
      label: '创建日期开始',
      componentProps: {
        placeholder: '请选择开始创建日期',
      }
    }, {
      field: 'birthday',
      component: 'NDatePicker',
      label: '创建日期结束',
      componentProps: {
        placeholder: '请选择结束创建日期'
      }
    }
  ]
  const roleSearchRef = ref({})

  /** 查询条件表单提交 */
  async function handleSearch(params: any) {
    getRoleList(params)
  }

  const title = ref('角色管理')
  const columns = ref([
    {
      title: '角色名',
      key: 'roleName',
      width: 120
    }, {
      title: '角色名',
      key: 'roleKey',
      width: 120
    }, {
      title: '状态',
      key: 'status',
      width: 60,
      align: 'center',
      render(row: any) {
        return selectDictLabel(statusOption.value, row.status)
      }
    }, {
      title: '创建日期',
      key: 'createTime',
      width: 230,
      align: 'center',
    }, {
    title: '操作',
    key: 'operate',
    width: 160,
    render: function(row) {
      return h(OperateButton, {
        buttonList: [
          { title: '编辑', type: 'info', size: 'small', onClick: () => handleEdit(row) },
          { title: '删除', type: 'error', size: 'small', onClick: () => handleDelete(row) }
        ]
      })
    }
  }
  ])

  /** table是否loading */
  const loading = ref(false)
  const baseUrl = '/system/role'

  /** 获取用户列表 */
  async function getRoleList(params: any) {
    loading.value = true
    const result = await list(baseUrl, { ...pageParams.value, ...params })
    data.value = result.data
    loading.value = false
  }

  /** tree选中的项 */
  const checkedKeys = ref<any>(['22'])
  /** tree展开的项 */
  const expandedKeys = ref<any>([])

  /** 选中、取消选中tree时 */
  function updateCheckedKeys(keys: any) {
    console.log('选中1', keys, checkedKeys.value)
    // checkedKeys.value = [checkedKeys.value, ...keys]
    checkedKeys.value.concat(keys)
    const tempArr = checkedKeys.value
    tempArr.concat(keys)
    console.log('选中2', tempArr)
  }

  function updateExpandedKeys(keys: any) {
    console.log('展开', keys)
    expandedKeys.value = [expandedKeys.value, ...keys]
  }

  const menuList = ref([])

  /** 获取菜单列表 */
  async function getMenuList() {
    const result = await listMenu(null);
    menuList.value = handleTree(result.data)
  }
  const showModal = ref(false)
  const btnLoading = ref(false)
  
  /** 新增时，表单的默认值 */
  const defaultForm = {
    status: '1'
  }
  
  /** 新增、编辑表单 */
  const form = ref({} as any)

  /** 表单标题 */
  const modalTitle = ref('添加角色')

  async function submitForm() {
    console.log('checkedKeys', unref(checkedKeys), form.value)
    form.value.menuIds = checkedKeys.value
    console.log('form', form.value)
    // btnLoading.value = true
    // const id = unref(form).id
    // if(id) {
    //   await updateRole(unref(form))
    //   $message.success('修改成功')
    // } else {
    //   await addRole(unref(form))
    //   $message.success('添加成功')
    // }
    // showModal.value = false
    // // roleSearchRef.value.handleSubmit()
    // btnLoading.value = false
  }



  onMounted(() => {
    getRoleList(null)
  })

  /** “添加”按钮 */
  function handleAdd() {
    checkedKeys.value = []
    expandedKeys.value = []
    modalTitle.value = '添加用户'
    showModal.value = true
    form.value = defaultForm
    getMenuList()
  }

  function handleEdit(row: any) {
    showModal.value = true
    getMenuList()
    getTreeSelectByRoleId(row.id).then(res => {
      // console.log('xx', checkedKeys.value, res.data)
      // checkedKeys.value = [res.data]
      // console.log(checkedKeys.value)
      checkedKeys.value = [ '1012', '1021']
    })
  }


</script>

<style>

</style>